<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/bootstrap.min.css">
<script src="/jquery.min.js"></script>
<script src="/bootstrap.min.js"></script>
<script src="/echarts.min.js"></script>
<title>自动打印系统</title>
</head>
<body 
	style="height: 100%; width: 99%; background-color: rgba(248, 249, 250, 0.8);">
	<!-- 提示框  -->
	<div
		style="position: fixed; top: 20px; right: 20px; width: auto; z-index: 1">
		<div class="alert alert-success alert-dismissable" id="alertSuccess"
			hidden="true">
			<button type="button" class="close" data-dismiss="alert"
				aria-hidden="true">&times;</button>
			<span id="alertSuccessText"></span>
		</div>
	</div>
	<div style=" width: 100%;">
		<!-- 第一行 -->
		<div class="row" style="height: 40%; weight: 100%">
			<!-- 控制打印机面板  -->
			<div class="col-4" style="padding: 10px 10px 10px 10px;">
				<div style="height: 100%; background-color: #ffffff">
					<table style="margin-left: 10px;" border=1 width="100%" frame=void
						rules=none>
						<tbody>
							<tr>
							<td><h3>平台编码:</h3></td>
							<td><h3>
									<span id="warehouse">无</span>
								</h3></td>
							</tr>	
							<tr>
								<td><h3>任务区间:</h3></td>
								<td><h3>
										<span id="stockCode">无</span>
									</h3></td>
							</tr>
							<tr>
								<td><h3>打印机IP:</h3></td>
								<td><h3>
										<span id="printerIp">无</span>
									</h3></td>
							</tr>
							<tr>
								<td><h3>打印机状态:</h3></td>
								<td><h3>
										<span id="printerStatus" class="badge badge-secondary">离线</span>
									</h3></td>
							</tr>
							<tr>
								<td><h3>今日完成数量:</h3></td>
								<td><h3>
										<span id="printerNumber">0</span>
									</h3></td>
							</tr>
						</tbody>
					</table>
					<button id="control" type="button" style="width: 100%"
						class="btn btn-secondary btn-sm" disabled=true>
						<span id="controlleValue">禁用</span>
					</button>

				</div>
			</div>
			<!-- 打印数量面板  -->
			<div class="col-4" style="padding: 10px 10px 10px 10px;">
				<div id="printNumber"
					style="height: 100%; background-color: #ffffff"></div>
			</div>
			<!-- 其他库区打印任务管理面板 -->
			<div class="col-4" style="padding: 10px 10px 10px 10px;">
				<div style="background-color: #ffffff;overflow-y: auto; height: 100%;">
					<table class="table">
						<thead class="thead-light">
							<tr>
								<th scope="col">序号</th>
								<th scope="col">平台编码</th>
								<th scope="col">任务区间</th>
								<th scope="col">状态</th>
								<th scope="col">操作</th>
							</tr>
						</thead>
						<tbody class="table table-hover table-striped" id="otherWarehouse"></tbody>
					</table>
				</div>
			</div>
		</div>
		<!-- 第二行 -->
		<div class="row" style="height: 55%; margin-top: 20px; weight: 100%">
			<!-- 当前等待打印任务 -->
			<div class="col-4"
				style="height: 100%; padding: 10px 10px 10px 10px;">
				<div style="background-color: #ffffff;">
					<table class="table">
						<thead class="thead-light">
							<tr>
								<th scope="col">待打印</th>
								<th scope="col">任务ID</th>
								<th scope="col">任务区间</th>
								<th scope="col">平台编码</th>
							</tr>
						</thead>
					</table>
				</div>
				<div style="height: 90%;overflow-y: auto; background-color: #ffffff;">
					<table class="table table-hover table-striped"
						style="  background-color: #ffffff;">
						<tbody id="awaitJob"></tbody>
					</table>
				</div>
			</div>
			<!-- 当前执行打印任务 -->
			<div class="col-4"
				style="height: 100%; padding: 10px 10px 10px 10px;">
				<div style="background-color: #ffffff;">
					<table class="table">
						<thead class="thead-light">
							<tr>
								<th scope="col">正在打印</th>
								<th scope="col">任务ID</th>
								<th scope="col">任务区间</th>
								<th scope="col">平台编码</th>
							</tr>
						</thead>
					</table>
				</div>
				<div style="height: 90%;overflow-y: auto; background-color: #ffffff;">
					<table class="table table-hover table-striped"
						style="  background-color: #ffffff;">
						<tbody id="executeJob"></tbody>
					</table>
				</div>
			</div>
			<!-- 历史打印任务 -->
			<div class="col-4"
				style="height: 100%; padding: 10px 10px 10px 10px;">
				<div style="background-color: #ffffff;">
					<table class="table">
						<thead class="thead-light">
							<tr>
								<th scope="col">历史打印</th>
								<th scope="col">任务ID</th>
								<th scope="col">时间</th>
								<th scope="col">操作</th>
							</tr>
						</thead>
					</table>
				</div>
				<div style="height: 90%;overflow-y: auto; background-color: #ffffff;">
					<table class="table table-hover table-striped"
						style="  background-color: #ffffff;">
						<tbody id="historyJob"></tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</body>
<script type="text/javascript">
	let pathname = location.pathname;
	let printerIp = pathname.substring(pathname.lastIndexOf('/')+1, pathname.length);
	let hostname = location.hostname;
	let port = location.port;
	let wsServer = 'ws://' + hostname + ':' + port + '/websocket/' + printerIp;
	let websocket = new WebSocket(wsServer);
	let ips = [];
    let onlinePrinter = [], normalPrinter = [], workingPrinter = [];
    let allStatus = {};
    let option = {
    		title: {
                text: '打印数量',
                subtext: "单/天",
                left: 'center'
            },
    	    tooltip: {
    	        trigger: 'axis',
    	        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
    	            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
    	        }
    	    },
    	    grid: {
    	        left: '3%',
    	        right: '4%',
    	        bottom: '3%',
    	        containLabel: true
    	    },
    	    xAxis: [
    	        {
    	            type: 'category',
    	            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    	            axisTick: {
    	                alignWithLabel: true
    	            }
    	        }
    	    ],
    	    yAxis: [
    	        {
    	            type: 'value'
    	        }
    	    ],
    	    series: [
    	        {
    	            name: '最近一周打印任务',
    	            type: 'bar',
    	            barWidth: '60%',
    	            data: [0, 0, 0, 0, 0, 0, 0]
    	        }
    	    ]
    	};
    
    document.getElementById("printerIp").innerHTML = printerIp;
    let printNumberPanel = echarts.init(document.getElementById('printNumber'));
	
	// 提示工具
    function tip(text) {
        document.getElementById('alertSuccessText').innerText = text;
        document.getElementById('alertSuccess').removeAttribute('hidden');
        setTimeout(function () {
            document.getElementById('alertSuccess').setAttribute('hidden','true');
        },2000);
    }
    
    // 启动IP为ip的打印机
    function start() {
        $.post("http://"+hostname+":"+port+"/printer/start/" + printerIp, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送启动打印机' + printerIp + '命令');
            }else{
                tip('发送启动打印机' + printerIp + '命令失败');
            }
        });
    }

    // 关闭IP为ip的打印机
    function stop() {
        $.post("http://"+hostname+":"+port+"/printer/stop/" + printerIp, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送关闭打印机' + printerIp + '命令');
            }else{
                tip('发送关闭打印机' + printerIp + '命令失败');
            }
        });
    }
    
    // 移除“打印其他库区”，ip1为被移除打印机，ip2为当前库区打印机
    function removeIP(ip1, ip2) {
        $.post("http://"+hostname+":"+port+"/printer/remove/" + ip1 + "/" + ip2, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送移除打印机'+ip2+'命令');
                document.getElementById(ip2 + 'control').setAttribute("class","btn btn-sm btn-primary")
				document.getElementById(ip2 + 'control').onclick= function(){addIP(ip1, ip2)};
				document.getElementById(ip2 + 'controlvalue').innerHTML = '添加';
            }
        })
    }

    // 添加“打印其他库区”，ip1为被添加打印机，ip2为当前库区打印机,即ip2点ip1任务
    function addIP(ip1, ip2) {
        $.post("http://"+hostname+":"+port+"/printer/add/" + ip1 + "/" + ip2, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送添加打印机'+ip2+'命令');
                document.getElementById(ip1 + 'control').setAttribute("class","btn btn-sm btn-warning");
				document.getElementById(ip1 + 'control').onclick= function(){removeIP(ip1, ip2)};
				document.getElementById(ip1 + 'controlvalue').innerHTML = '移除';
            }
        })
    }
    
    // 重新打印
    function rePrint(msgId){
    	console.log("http://"+hostname+":"+port+"/printer/reprint/" + printerIp + "/" + msgId)
    	$.post("http://"+hostname+":"+port+"/printer/reprint/" + printerIp + "/" + msgId, function (data) {
            if (data === true || data === 'true') {
                tip('成功发送重新打印'+msgId+'命令');
            }
        })
    }
    
    // 初始化打印机
    function init(){
    	$.post("http://"+hostname+":"+port+"/printer/init", function (data) {
            if (data === true || data === 'true') {
                tip('成功发送初始化打印机命令');
            }
        })
    }
    
    // 关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    // 连接发生错误的回调方法
    websocket.onerror = function () {
        console.log("WebSocket连接发生错误");
    };

    // 连接成功建立的回调方法
    websocket.onopen = function () {
        console.log("WebSocket连接成功");
    }

    // 连接关闭的回调方法
    websocket.onclose = function () {
        console.log("连接关闭")
        websocket = new WebSocket(wsServer);
    }

    // 监听窗口关闭事件，当窗口关闭时，主动去关闭webSocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    // 接收到消息的回调方法
    websocket.onmessage = function (event) {
        const data = JSON.parse(event.data);
        if (data.code === 0) {
            // 获取所有打印机
            ips = data.ips;
            let templateData = "";
            let i = 0;
            ips.forEach(function(item,index){
	            if(item !== printerIp){
	            	i = i + 1;
	            	templateData = templateData + '<tr>'
		            	+ '<td>' + i + '</td>'
		            	+ '<td><span id="' + item + 'warehouse">无</span></td>'
						+ '<td><span id="' + item + 'stockCode">无</span></td>'
		            	+ '<td><span id="' + item + 'status" class="badge badge-secondary">无 </span></td>'
		            	+ '<td><button id="' + item + 'control" type="button" class="btn btn-primary btn-sm"><span id="' + item + 'controlvalue">添加 </span></button></td>'
		            	+ '</tr>';
	            }
            });
            document.getElementById("otherWarehouse").innerHTML = templateData;
        } else if (data.code === 1 || data.code === '1') {
        	console.log(data)
        	allStatus[data.ip] = data;
            // 更新联网数据
            if (onlinePrinter.includes(data.ip) && (data.offline === true || data.offline === 'true')) {
                let temp = [];
                onlinePrinter.forEach(function (d) {
                    if (d !== data.ip) {
                        temp.push(d);
                    }
                });
                onlinePrinter = temp;
                temp = [];
                if(normalPrinter.includes(data.ip)){
                    normalPrinter.forEach(function (d) {
                        if (d !== data.ip) {
                            temp.push(d);
                        }
                    });
                    normalPrinter = temp;
                }
                temp = [];
                if(workingPrinter.includes(data.ip)){
                    workingPrinter.forEach(function (d) {
                        if (d !== data.ip) {
                            temp.push(d);
                        }
                    });
                    workingPrinter = temp;
                }
            }
            if (!onlinePrinter.includes(data.ip) && (data.offline === false || data.offline === 'false')) {
                onlinePrinter.push(data.ip);
            }

            // 更新脱机数据
            if (normalPrinter.includes(data.ip) && (data.esc.status.offLine === true || data.esc.status.offLine === 'true')) {
                let temp = [];
                normalPrinter.forEach(function (d) {
                    if (d !== data.ip) {
                        temp.push(d);
                    }
                });
                normalPrinter = temp;
                temp = [];
                if(workingPrinter.includes(data.ip)){
                    workingPrinter.forEach(function (d) {
                        if (d !== data.ip) {
                            temp.push(d);
                        }
                    });
                    workingPrinter = temp;
                }
            }
            if (!normalPrinter.includes(data.ip) && onlinePrinter.includes(data.ip) && (data.esc.status.offLine === false || data.esc.status.offLine === 'false')) {
                normalPrinter.push(data.ip);
            }

            // 更新工作数据
            if (workingPrinter.includes(data.ip) && (data.run === false || data.run === 'false')) {
                const temp = [];
                workingPrinter.forEach(function (d) {
                    if (d !== data.ip) {
                        temp.push(d);
                    }
                });
                workingPrinter = temp;
            }
            if (!workingPrinter.includes(data.ip) && onlinePrinter.includes(data.ip) && (data.run === true || data.run === 'true')) {
                workingPrinter.push(data.ip);
            }
        }
		updatePage();
    }
    
    function updatePage(){
    	update1();
    	update2();
    	update3();
    	update4();
    	update5();
    	update6();
    }
    
    function update1(){
    	if(allStatus[printerIp] !== undefined && allStatus[printerIp] !== 'undefined' ){
    		document.getElementById("warehouse").innerHTML = allStatus[printerIp].name;
    		document.getElementById("stockCode").innerHTML = allStatus[printerIp].stockCode;
        	document.getElementById("printerNumber").innerHTML = allStatus[printerIp].printHistory[6];
    	}
    	if(!onlinePrinter.includes(printerIp)){
    		document.getElementById("printerStatus").innerHTML = "离线";
    		document.getElementById("control").disabled = true;
    		document.getElementById("control").setAttribute("class", "btn btn-sm btn-secondary");
    		document.getElementById("controlleValue").innerHTML = "禁用";
    		document.getElementById("printerStatus").setAttribute("class","badge badge-secondary");
    	}else if(!normalPrinter.includes(printerIp)){
    		document.getElementById("printerStatus").innerHTML = "脱机(故障)";
    		document.getElementById("printerStatus").setAttribute("class","badge badge-danger");
    		document.getElementById("control").disabled = true;
    		document.getElementById("control").setAttribute("class", "btn btn-sm btn-secondary");
    		document.getElementById("controlleValue").innerHTML = "禁用";
    	}else if(workingPrinter.includes(printerIp)){
    		document.getElementById("printerStatus").innerHTML = "运行中";
    		document.getElementById("printerStatus").setAttribute("class","badge badge-success");
    		document.getElementById("control").disabled = false;
    		document.getElementById("control").setAttribute("class", "btn btn-sm btn-warning");
    		document.getElementById("controlleValue").innerHTML = "终止";
    		document.getElementById("control").onclick= function(){stop()};
    	}else{
    		document.getElementById("printerStatus").innerHTML = "空闲中";
    		document.getElementById("printerStatus").setAttribute("class","badge badge-primary");
    		document.getElementById("control").disabled = false;
    		document.getElementById("control").setAttribute("class", "btn btn-sm btn-primary");
    		document.getElementById("controlleValue").innerHTML = "启动";
    		document.getElementById("control").onclick= function(){start()};
    	}
    }
    
    function update2(){
    	if(allStatus[printerIp] !== undefined && allStatus[printerIp] !== 'undefined' ){
    		let d = new Date()
    		option.xAxis[0].data=[getDay(-6),getDay(-5),getDay(-4),getDay(-3),getDay(-2),getDay(-1),getDay(0)];
        	option.series[0].data=allStatus[printerIp].printHistory;
        	printNumberPanel.setOption(option);
    	}
    }
    
    function update3(){
    	ips.forEach(function(item, index){
			if(item !== printerIp && allStatus[item] !== undefined && allStatus[item] !== 'undefined'){
				document.getElementById(item + 'warehouse').innerHTML = allStatus[item].name;
				document.getElementById(item + 'stockCode').innerHTML = allStatus[item].stockCode;
				if(!onlinePrinter.includes(item)){
					document.getElementById(item + 'status').innerHTML = '离线';
					document.getElementById(item + 'status').setAttribute("class","badge badge-secondary");
				}else if(!normalPrinter.includes(item)){
					document.getElementById(item + 'status').innerHTML = '脱机(故障)';
					document.getElementById(item + 'status').setAttribute("class","badge badge-danger");
				}else if(workingPrinter.includes(item)){
					document.getElementById(item + 'status').innerHTML = "运行中";
					document.getElementById(item + 'status').setAttribute("class","badge badge-success");
				}else{
					document.getElementById(item + 'status').innerHTML = "空闲中";
					document.getElementById(item + 'status').setAttribute("class","badge badge-primary");
				}
				if(allStatus[printerIp].otherIp.includes(item)){
					document.getElementById(item + 'control').setAttribute("class","btn btn-sm btn-warning");
					document.getElementById(item + 'control').onclick= function(){removeIP(item, printerIp)};
					document.getElementById(item + 'controlvalue').innerHTML = '移除';
				}else{
					document.getElementById(item + 'control').setAttribute("class","btn btn-sm btn-primary")
					document.getElementById(item + 'control').onclick= function(){addIP(item, printerIp)};
					document.getElementById(item + 'controlvalue').innerHTML = '添加';
				}
			}
		});
    }
    
    function update4(){
    	if(allStatus[printerIp] !== undefined && allStatus[printerIp] !== 'undefined' ){
    		let data = "";
    		let i = 0;
        	allStatus[printerIp].awaitTask.forEach(function(item, index){
    			i = i +1;
        		data = data + '<tr>' 
    			+ '<td>' + i + '</td>'
    			+ '<td>' + ((item.messageId === 0 || item.messageId === '0') ? item.messageIds :item.messageId) + '</td>'
    			+ '<td>' + item.stockCode + '</td>'
    			+ '<td>' + item.warehouseCode + '</td>'
    			+ '</tr>';
    		});
    		document.getElementById('awaitJob').innerHTML = data;
    	}
    }
    
    function update5(){
    	if(allStatus[printerIp] !== undefined && allStatus[printerIp] !== 'undefined' ){
    		let data = "";
    		let i = 0;
        	allStatus[printerIp].currentTask.forEach(function(item, index){
    			i = i +1;
        		data = data + '<tr>' 
    			+ '<td>' + i + '</td>'
    			+ '<td>' + ((item.messageId === 0 || item.messageId === '0') ? item.messageIds :item.messageId) + '</td>'
    			+ '<td>' + item.stockCode + '</td>'
    			+ '<td>' + item.warehouseCode + '</td>'
    			+ '</tr>';
    		});
    		document.getElementById('executeJob').innerHTML = data;
    	}
    }
    
    function update6(){
    	if(allStatus[printerIp] !== undefined && allStatus[printerIp] !== 'undefined' ){
    		let data = "";
    		let i = 0;
        	allStatus[printerIp].historyTask.forEach(function(item, index){
    			i = i + 1;
    			
        		data = data + '<tr>' 
    			+ '<td>' + i + '</td>'
    			+ '<td>' + item.messageId + '</td>'
    			+ '<td>' + dateUtil(item.lastTime) + '</td>'
    			+ '<td><button class="btn btn-sm btn-warning" onclick="rePrint(\'' + item.messageId + '\')">重新打印</button></td>'
    			+ '</tr>';
    		});
    		document.getElementById('historyJob').innerHTML = data;
    	}
    }
    
    function dateUtil(timestamp){
    	var date = new Date(timestamp);
    	return date.getFullYear() + "-" 
    		+ (date.getMonth()+1<10?'0'+(date.getMonth()+1):date.getMonth()+1) + "-"
    		+ date.getDate() + " "
    		+ date.getHours() + ":"
    		+ date.getMinutes() + ":"
    		+ date.getSeconds();
    }

    function getDay(day){  
           var today = new Date();  
             
           var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;          
      
           today.setTime(targetday_milliseconds); // 注意，这行是关键代码
             
           var tYear = today.getFullYear();  
           var tMonth = today.getMonth();  
           var tDate = today.getDate();  
           tMonth = doHandleMonth(tMonth + 1);  
           tDate = doHandleMonth(tDate);  
           return tYear+"-"+tMonth+"-"+tDate;  
    }
    
    function doHandleMonth(month){
           var m = month;
           if(month.toString().length == 1){  
              m = "0" + month;  
           }  
           return m;
    }
    
</script>

</html>